package com.lx.huimail.fragment.backorder;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.lx.huimail.R;
import com.lx.huimail.adapter.PubAdapter;
import com.lx.huimail.configs.Config;
import com.lx.huimail.fragment.BackGoodsFragment;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Pattern;

import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class BackDetialFragment extends Fragment {
    private TextView exiteno,name,phone,address,peisongStatus;
    private TextView payMethod,psTime,getTime,allMoney,realMoney,createTime;
    private RecyclerView recyclerView;
    private String orderNo="";
    private String exiteNo="";

    private String custid="";
    private String status="0";
    private Button beginBack,psResult;
    private LocationClient mLocClient;
    private String province, city, district;
    private String  latitude="", lontitude="";
    private String isGolds="0";
    public static String TAG = "LocTestDemo";
    private String Id="";
    private RelativeLayout rpayMethod;
    private LinearLayout sendTime,finishTime;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_order_detial, container, false);
        mLocClient =new LocationClient(getActivity());
        mLocClient.registerLocationListener( new MyLocationListenner());
        setLocationOption();
        mLocClient.start();

        initViews(view);
        SharedPreferences sp=getContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        custid=sp.getString("custid","-11111");
        orderNo=getActivity().getIntent().getStringExtra("orderno");
        exiteNo=getActivity().getIntent().getStringExtra("exiteno");
        Id=getActivity().getIntent().getStringExtra("id");
        status=getActivity().getIntent().getStringExtra("status");
        isGolds=getActivity().getIntent().getStringExtra("isgolds");

        exiteno.setText(exiteNo);
        if(status.equals("-1")){
            peisongStatus.setText("未分配配送员");
        }else if(status.equals("0")){
            peisongStatus.setText("等待退货");
      //      beginBack.setVisibility(View.VISIBLE);
            beginBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startBack(lontitude,latitude);
                }
            });
        }else if(status.equals("1")){
            peisongStatus.setText("退货完成");
        }else if(status.equals("2")){
            peisongStatus.setText("退货中");
            psResult.setVisibility(View.VISIBLE);
        }

        getOrderInfoByOrderno();
        return view;
    }

    private void initViews(View view){

        recyclerView=(RecyclerView)view.findViewById(R.id.recyclerview);
        exiteno=(TextView)view.findViewById(R.id.orderno);
        name=(TextView)view.findViewById(R.id.xingming);
        phone=(TextView)view.findViewById(R.id.phone);
        address=(TextView)view.findViewById(R.id.tv3);
        peisongStatus=(TextView)view.findViewById(R.id.tv_status);
        beginBack=(Button) view.findViewById(R.id.begin);
        psResult=(Button) view.findViewById(R.id.ps_result);

        payMethod=(TextView)view.findViewById(R.id.ps_method);
        psTime=(TextView)view.findViewById(R.id.ps_time);
        getTime=(TextView)view.findViewById(R.id.get_time);
        allMoney=(TextView)view.findViewById(R.id.allprice);
        realMoney=(TextView)view.findViewById(R.id.realmoney);
        createTime=(TextView)view.findViewById(R.id.createtime);
        psResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishTh(lontitude,latitude);
            }
        });

        rpayMethod=(RelativeLayout)view.findViewById(R.id.rll5);
        sendTime=(LinearLayout) view.findViewById(R.id.rll6);
        finishTime=(LinearLayout)view.findViewById(R.id.rll7);
        rpayMethod.setVisibility(View.GONE);
        sendTime.setVisibility(View.GONE);
        finishTime.setVisibility(View.GONE);


    }

    /**
     * 通过订单号获取商品信息
     */
    private void getOrderInfoByOrderno(){
        HashMap<String,String> map=new HashMap<>();
        map.put("exiteno",exiteNo);
        map.put("page","1");
        map.put("rows","1000000");
        Gson gson=new Gson();
        String parmas=gson.toJson(map);
        OkHttpUtils
                .post()
                .url(Config.url+"send/searchExiteOrder.do")
                .addParams("data",parmas)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                        Toast.makeText(getContext(),"链接服务器失败",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.print("退货单详情=="+response);
                        getExitIfnoById();
                        JSONArray jsonArray=null;
                        JSONObject jsonObject=null;

                        try {
                            jsonObject=new JSONObject(response);
                            jsonArray=jsonObject.getJSONArray("list");
                            for (int i=0;i<jsonArray.length();i++){
                                jsonObject=jsonArray.getJSONObject(i);

                                exiteno.setText(jsonObject.getString("exiteno"));
                                name.setText(jsonObject.getString("custname"));
                                if(jsonObject.getString("custphone").equals("null")){
                                    phone.setText("");
                                }
                                phone.setText(jsonObject.getString("custphone"));

                                address.setText(jsonObject.getString("exiteaddress"));

                                psTime.setText("");
                                getTime.setText("");
                                allMoney.setText(jsonObject.getString("exitmoney"));
                                realMoney.setText(jsonObject.getString("exitmoney"));
                                createTime.setText(getTime(jsonObject.getString("createtime")));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    /**
     *开始退货
     */
    private void startBack(String longitude,String latitude){
        if(longitude.equals("4.9E-324")||latitude.equals("4.9E-324")){
            longitude="";
            latitude="";
        }
        HashMap<String,String> map=new HashMap<>();
        map.put("exiteno",exiteNo);
        map.put("longitude",longitude);
        map.put("latitude",latitude);
        map.put("senderid",custid);
        Gson gson=new Gson();
        String parmas=gson.toJson(map);
        OkHttpUtils
                .post()
                .url(Config.url+"send/sendBeginExiteProduct.do")
                .addParams("data",parmas)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(getContext(),"服务器连接超时",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        if (response.equals("true")){
                            Toast.makeText(getContext(),"确认退货成功",Toast.LENGTH_SHORT).show();
                            getActivity().finish();
                            BackGoodsFragment.getBackGoodsInfo("");

                        }else {
                            Toast.makeText(getContext(),"确认退货失败，请重新确认",Toast.LENGTH_SHORT).show();
                        }

                    }
                });
    }
    private String getTime(String time){
        if(!time.equals("null")){
            Date date=new Date(Long.valueOf(time));
            SimpleDateFormat format;
            format=new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return format.format(date);
        }else {
            return "";
        }
    }
    //设置相关参数
    private void setLocationOption(){
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);				//设置是否打开gps，使用gps前提是用户硬件打开gps。默认是不打开gps的。
        option.setCoorType("bd09ll");		//设置坐标类型
        option.setServiceName("com.baidu.location.service_v2.9");
        option.setPoiExtraInfo(true);//设置是否需要POI的电话地址等详细信息
        option.setPoiNumber(10);
        option.setAddrType("all");//	设置是否要返回地址信息，默认为无地址信息。String 值为 all时，表示返回地址信息。其他值都表示不返回地址信息。
        option.setScanSpan(3000);	//设置定位模式，小于1秒则一次定位;大于等于1秒则定时定位
        option.setPriority(LocationClientOption.NetWorkFirst);      //设置网络优先,/不设置，默认是gps优先
        option.disableCache(true);
        mLocClient.setLocOption(option);
    }

    /**
     * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return;
            StringBuffer sb = new StringBuffer(256);
            latitude=String .valueOf(location.getLatitude());
            lontitude=String.valueOf(location.getLongitude());
            if (location.getLocType() == BDLocation.TypeGpsLocation){
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
                province = location.getProvince();
                city = location.getCity();
                district = location.getDistrict();
            }
            logMsg(latitude+lontitude);

        }
        /**
         * 显示字符串
         * @param str
         */
        public void logMsg(String str) {
            try {
                System.out.print("经纬度=="+str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onReceivePoi(BDLocation arg0) {
            // TODO Auto-generated method stub

        }

    }
    protected boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }
    /**
     * 检查GPS是否开启
     * @return
     */
    public boolean isGPSEnabled(){
        LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }
    /**
     * 打开gps设置界面
     */
    public void openGPSSetting(){
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            this.startActivity(intent);

        }catch(ActivityNotFoundException ex){

            // The Android SDK doc says that the location settings activity
            // may not be found. In that case show the general settings.

            // General settings activity
            intent.setAction(Settings.ACTION_SETTINGS);
            try {
                this.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onDestroy() {
        mLocClient.stop();
        super.onDestroy();
    }

    /**
     * 完成退货
     */
    private void finishTh(String longitude,String latitude){
        if(longitude.equals("4.9E-324")||latitude.equals("4.9E-324")){
            longitude="";
            latitude="";
        }
        HashMap<String,String> map=new HashMap<>();
        map.put("exiteno",exiteNo);
        map.put("longitude",longitude);
        map.put("latitude",latitude);
        map.put("custid",custid);
        map.put("orderno",orderNo);
        map.put("isgolds",isGolds);

        Gson gson=new Gson();
        String parmas=gson.toJson(map);
        OkHttpUtils
                .post()
                .url(Config.url+"send/sendExiteProduct.do")
                .addParams("data",parmas)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Toast.makeText(getActivity(),"退货完成",Toast.LENGTH_LONG).show();
                        getActivity().finish();
                        BackGoodsFragment.getBackGoodsInfo("");

                    }
                });
    }

    private void getExitIfnoById(){
        HashMap<String,String> map=new HashMap<>();
        map.put("id",Id);
        Gson gson=new Gson();
        String parmas=gson.toJson(map);
        OkHttpUtils
                .post()
                .url(Config.url+"send/searchExiteOrderDetail.do")
                .addParams("data",parmas)
                .addParams("mobile","true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONArray jsonArray=null;
                        JSONObject jsonObject=null;
                        ArrayList<HashMap<String,Object>> mapArrayList=new ArrayList<HashMap<String, Object>>();

                        try {
                            jsonArray=new JSONArray(response);
                            for (int i=0;i<jsonArray.length();i++){
                                HashMap<String,Object> map1=new HashMap<String, Object>();
                                jsonObject=jsonArray.getJSONObject(i);
                                map1.put("price",jsonObject.getString("saleprice"));
                                map1.put("proname",jsonObject.getString("proname"));
                                map1.put("count",jsonObject.getString("exitecount"));
                                map1.put("picname", Config.url+"tmp/"+jsonObject.getString("picname"));
                                mapArrayList.add(map1);
                            }
                            PubAdapter myAdapter=new PubAdapter(getContext(),mapArrayList);
                            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                            recyclerView.setAdapter(myAdapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

}
